/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mighty.team.homemediacenterdescriptor.dao;

import com.mighty.team.homemediacenterdescriptor.model.Movie;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author TSokolowski
 */
@Transactional
@Repository("movieDAOImpl")
public class MovieDAOImpl implements MovieDAO {

    @Autowired    
    private SessionFactory sessionFactory;

    public Session getCurrentSessionFactory() {
        return sessionFactory.getCurrentSession();
    }

    
    public void addMovie(Movie movie) {
        getCurrentSessionFactory().save(movie);
    }

    
    public void updateMovie(Movie movie) {
        Movie movieToUpdate = getMovie(movie.getId());
        movieToUpdate.setTitle(movie.getTitle());
        movieToUpdate.setDescription(movie.getDescription());
        movieToUpdate.setGenre(movie.getGenre());
        movieToUpdate.setYear(movie.getYear());
        movieToUpdate.setQuality(movie.getQuality());
        getCurrentSessionFactory().update(movie);
    }

    
    public Movie getMovie(int id) {
        Movie movie = (Movie) getCurrentSessionFactory().get(Movie.class, id);
        return movie;
    }

    
    public void removeMovie(int id) {
        Movie movie = getMovie(id);
        if (movie != null) {
            getCurrentSessionFactory().delete(movie);
        }
    }

    
    @SuppressWarnings("unchecked")
    public List<Movie> getMovies() {
        return getCurrentSessionFactory().createQuery("from Movie").list();
    }
}
